package com.anxinr.controller;

import com.anxinr.pojo.entity.Project;
import com.anxinr.pojo.entity.Users;
import com.anxinr.result.Result;
import com.anxinr.service.IProjectService;
import com.anxinr.service.IUsersService;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Objects;

/**
 * @author anxinr
 */
@Slf4j
@RestController
@RequestMapping("/project")
public class ProjectController {
    @Autowired
    private IProjectService projectService ;
    @Autowired
    private IUsersService usersService ;

    @PostMapping("/query")
    public Result<IPage<Project>> query(@RequestBody Project project ){
        return new Result(projectService.queryProject(project)) ;
    }

    @PostMapping("/save")
    public Result save(@RequestBody Project project , HttpServletRequest request) throws Exception {
        try {
            String token = request.getHeader("token");
            Users users = usersService.getById(token);
            if (Objects.isNull(users)){
                throw new Exception("请登录！") ;
            }
            project.setUser(users.getName());
            project.setTime(new Date());
            projectService.save(project);
        }catch (Exception e){
            e.printStackTrace();
            throw e ;
        }
        return Result.success() ;
    }

    @PostMapping("/update")
    public Result update(@RequestBody Project project , HttpServletRequest request){
        try {
            String token = request.getHeader("token");
            Users users = usersService.getById(token);
            project.setUser(users.getName());
            project.setTime(new Date());
            projectService.updateById(project);
        }catch (Exception e){
            e.printStackTrace();
            throw e ;
        }
        return Result.success() ;
    }

    @GetMapping("/remove")
    public Result remove(@RequestParam("pname") String pname){
        try {
            LambdaUpdateWrapper<Project> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(Project::getPname,pname);
            projectService.remove(wrapper) ;
        }catch (Exception e){
            e.printStackTrace();
            throw e ;
        }
        return Result.success() ;
    }


}
